//
//  ContactsViewController.m
//  AAIM
//
//  Created by awh on 2019/11/24.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "ContactsViewController.h"
#import "FriendsInfoViewController.h"
#import "NewFroendsViewController.h"
#import "ChatViewController.h"

#import "XLPopMenuViewSingleton.h"
#import "XLPopMenuViewModel.h"

#import "ContactsCell.h"
#import "EMChineseToPinyin.h"
#import "ContactModel.h"

#import "ContactRequestLogic.h"

#import "SearchFriendsViewController.h"
#import "PSWJoinGroupVC.h"
#import "SearchResultsVC.h"
#import "PublicViewController.h"
//#import <Contacts/Contacts.h>
//#import <ContactsUI/ContactsUI.h>

@interface ContactsViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
{
    UIButton * markBtn;
    NSInteger markIndx;//记录点击的是联系人还是群组
}
@property (nonatomic , strong) NSMutableArray *items;

@property (nonatomic, strong) NSMutableArray<NSString *> *sectionTitles;
@property (nonatomic, strong) UITableView * contactsTable;//Friends
@property (nonatomic, strong) NSMutableArray *dataSources;
@property (nonatomic, strong) UIView*navView;

@property (nonatomic, strong) UIScrollView*bgScrollView;
@property (nonatomic, strong) UITableView*groupsTable;//Group
@property (nonatomic, strong) NSMutableArray *groupDataSources;
@property (nonatomic,strong) MJTableViewNullDataView * nullDataView;
//@property (nonatomic,assign)NSInteger isRecommend;//1推荐通讯录好友，0不推荐
//@property (nonatomic,copy) NSMutableArray * addressBookFriendAry;//通讯录好友
@property (nonatomic,copy) NSString * sectionType;//0是我创建的，1是我加入的群聊
@end

@implementation ContactsViewController
@synthesize items = _items;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    self.navigationController.navigationBar.hidden=YES;
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"加 (1)"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnDidClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn sizeToFit];
    rightBtn.frame = CGRectMake(0, 0, 25, 25);
    rightBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(10, 10, 10, 10);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIButton *rightSearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightSearchBtn setImage:[UIImage imageNamed:@"搜索按钮"] forState:UIControlStateNormal];
    [rightSearchBtn addTarget:self action:@selector(rightSearchClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightSearchBtn sizeToFit];
    rightSearchBtn.frame = CGRectMake(0, 0, 25, 25);
    rightSearchBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(10, 10, 10, 10);
    UIBarButtonItem *rightSearchItem = [[UIBarButtonItem alloc] initWithCustomView:rightSearchBtn];
    
    self.gk_navigationItem.rightBarButtonItems = @[rightItem,rightSearchItem];
    markIndx = 100;

//       [self getMailListAction];//获取通讯录权限
   
    //刷新数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithGroupData) name:kMessageSystemCreateGroup object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithContactData) name:kMessageSystemAddFriends object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNewFriendNum) name:kMessageSystemSetRedDot object:nil];


}
-(void)refreshNewFriendNum
{
    PublicButton * markBtn =[self.view viewWithTag:10086];
    [self setNewFriendNum:markBtn];
}
-(void)rightBtnDidClickAction:(UIButton*)sender
{
    [YCXMenu setTintColor:[UIColor whiteColor]];
    [YCXMenu setTitleFont:[UIFont systemFontOfSize:14]];
    [YCXMenu hasShadow];
    [YCXMenu setHasShadow:YES];
    [YCXMenu setSeparatorColor:KHEXCOLOR(@"#E0E0E0")];
    [YCXMenu setSelectedColor:KHEXCOLOR(@"#E0E0E0")];
    if ([YCXMenu isShow]){
        [YCXMenu dismissMenu];
    } else {
        CGFloat y = IS_iPhoneX ? 88  : 64 ;
        [YCXMenu showMenuInView:self.view fromRect:CGRectMake(self.view.frame.size.width - 48, y-10, 40, 0) menuItems:self.items selected:^(NSInteger index, YCXMenuItem *item) {
            if(index==0){
                SearchFriendsViewController * searchVC = [[SearchFriendsViewController alloc]init];
                searchVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:searchVC animated:YES];
            }else if(index==1)
            {
                PSWJoinGroupVC*joinGroupVC=[[PSWJoinGroupVC alloc]init];
                joinGroupVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:joinGroupVC animated:YES];
            }
        }];
    }
}
- (NSMutableArray *)items {
    if (!_items) {
        _items = [@[[YCXMenuItem menuItem:@"添加好友"
                                    image:[UIImage imageNamed:@"icon-添加好友"]
                                      tag:99
                                 userInfo:@{@"title":@"Menu"}],
                    [YCXMenuItem menuItem:@"口令进群"
                                    image:[UIImage imageNamed:@"icon-口令进群"]
                                      tag:100
                                 userInfo:@{@"title":@"Menu"}]
                    ] mutableCopy];
    }
    return _items;
}
- (void)setItems:(NSMutableArray *)items {
    _items = items;
}
- (void)rightSearchClickAction:(UIButton *)sender {
    SearchResultsVC * searchVC=[[SearchResultsVC alloc]init];
          searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
      
}

-(void)setUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.contactsTable.tableHeaderView=[self tableHeaderView];
    [self.view addSubview:self.bgScrollView];
    [self.bgScrollView addSubview:self.contactsTable];
    [self.bgScrollView addSubview:self.groupsTable];
//    [self.groupsTable addSubview:self.nullDataView];
//    [self showAlwaysTipHudWithText:@"加载中，请稍等"];
//    self.bgScrollView.contentSize = CGSizeMake(2*kScreenWidth, kScreenHeight);
    [self.bgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
//        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.top.equalTo(self.gk_navigationBar.mas_bottom);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
    [self.contactsTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(SCREEN_WIDTH));
        make.top.equalTo(self.bgScrollView).offset(0);
        make.bottom.equalTo(self.mas_bottomLayoutGuide);
    }];
    [self.groupsTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(SCREEN_WIDTH));
        make.width.equalTo(@(SCREEN_WIDTH));
        make.top.equalTo(self.bgScrollView).offset(10);
        make.bottom.equalTo(self.mas_bottomLayoutGuide);
    }];
    
//    self.gk_navigationItem.titleView=self.navView;
    self.gk_navigationItem.titleView = self.navView;
      KWeakSelf;
     [self dealWithContactData];
    [self dealWithGroupData];
    _groupsTable.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.groupDataSources removeAllObjects];
        [weakSelf.sectionTitles removeAllObjects];
        [weakSelf dealWithGroupData];
    }];
//    [self.groupsTable.mj_header beginRefreshing];//代表着开始刷新
    _contactsTable.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.dataSources removeAllObjects];
              [weakSelf dealWithContactData];
    }];

}
//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    if (markIndx == 101) {
//        [self setAnimtiomL:markIndx];
//    }
//}
-(void)dealWithContactData
{
    NSArray * friendArray=  [[UserDataBaseTool shareUserDataBaseTool] queryAllFriends];
    NSMutableArray *contactArray = [NSMutableArray array];

    [friendArray enumerateObjectsUsingBlock:^(ContactModel *  obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [contactArray addObject:obj];
    }];
    [self sortAllContacts:contactArray];
    [self.contactsTable.mj_header endRefreshing];
    [self.contactsTable reloadData];
}

- (void)dealWithGroupData{
      //群组
      [self.groupDataSources removeAllObjects];
      NSMutableArray * createGroups=[NSMutableArray new];
      NSMutableArray * joinGroups=[NSMutableArray new];
      NSArray * groupArray=  [[UserDataBaseTool shareUserDataBaseTool] queryAllGroups];
     [groupArray enumerateObjectsUsingBlock:^(ContactModel *  obj, NSUInteger idx, BOOL * _Nonnull stop) {
         if (obj.isMeCreate==1) {
             [createGroups addObject:obj];
         }else
         {
             [joinGroups addObject:obj];
         }
    }];
    if (createGroups.count>0&&joinGroups.count>0 ) {
        [self.groupDataSources addObject:createGroups];
           [self.groupDataSources addObject:joinGroups];
        self.nullDataView.hidden = YES;
    }else if (createGroups.count>0 &&joinGroups.count==0){
        [self.groupDataSources addObject:createGroups];
        [self.groupDataSources addObject:joinGroups];
        self.sectionType = @"0";
         self.nullDataView.hidden = YES;
    }else if (createGroups.count==0&&joinGroups.count>0){
           [self.groupDataSources addObject:joinGroups];
        [self.groupDataSources addObject:createGroups];
        self.sectionType = @"1";
         self.nullDataView.hidden = YES;
    }else{
       [self.groupDataSources addObject:createGroups];
       [self.groupDataSources addObject:joinGroups];
    }
   
    [self.groupsTable reloadData];
    [self.groupsTable.mj_header endRefreshing];
  

}

////获取通讯录
//- (void)getMailListAction{
//    KWeakSelf;
//    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
//    if (status == CNAuthorizationStatusNotDetermined) {
//        CNContactStore *store = [[CNContactStore alloc] init];
//        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
//            if (error) {
//                //无权限
//                weakSelf.isRecommend = 0;
//            } else {
//                //有权限
//                weakSelf.isRecommend = 1;
//                [self openContact];
//            }
//        }];
//    } else if(status == CNAuthorizationStatusRestricted) {
//        //无权限
//        weakSelf.isRecommend = 0;
//
//    } else if (status == CNAuthorizationStatusDenied) {
//        //无权限
//        weakSelf.isRecommend = 0;
//
//    } else if (status == CNAuthorizationStatusAuthorized) {
//        //有权限
//           [self openContact];
//
//        weakSelf.isRecommend = 1;
//
//    }
//    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld",(long)_isRecommend] forKey:[NSString stringWithFormat:@"recommendFriends_%@",UserFuuid]];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//
//}
//
//- (void)openContact{
//    if (self.isRecommend == 0) {
//      self.isRecommend = 1;
//    }
//    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%ld",(long)_isRecommend] forKey:[NSString stringWithFormat:@"recommendFriends_%@",UserFuuid]];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
//    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
//    CNContactStore *contactStore = [[CNContactStore alloc] init];
//        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
//  __block NSString * jsonStr;
//    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
//        NSString * firstName = contact.familyName;
//        NSString * lastName = contact.givenName;
//        //电话
//        NSArray * phoneNums = contact.phoneNumbers;
//        CNLabeledValue *labelValue = phoneNums.firstObject;
//        NSString *phoneValue = [labelValue.value stringValue];
//        if ([phoneValue containsString:@"-"]||[phoneValue containsString:@" "]) {
//            if ([phoneValue containsString:@"-"]) {
//               NSArray * phones = [phoneValue componentsSeparatedByString:@"-"];
//                NSString * phoneStr;
//                for (int i=0; i<phones.count; i++) {
//                    if (i==0) {
//                     phoneStr = [NSString stringWithFormat:@"%@",phones[i]];
//                    }else{
//                       phoneStr = [NSString stringWithFormat:@"%@%@",phoneStr,phones[i]];
//                    }
//                }
//                phoneValue = phoneStr;
//            }else{
//               NSArray * phones = [phoneValue componentsSeparatedByString:@" "];
//                NSString * phoneStr;
//                for (int i=0; i<phones.count; i++) {
//                    if (i==0) {
//                     phoneStr = [NSString stringWithFormat:@"%@",phones[i]];
//                    }else{
//                       phoneStr = [NSString stringWithFormat:@"%@%@",phoneStr,phones[i]];
//                    }
//                }
//                phoneValue = phoneStr;
//            }
//        }
//        if (phoneValue) {
//          [dic setValue:[NSString stringWithFormat:@"%@%@",firstName,lastName] forKey:phoneValue];
//        }
//
//
//
//    }];
//    if (dic.count !=0) {
//    jsonStr = [self convertToJsonData:dic];
//    }
//    [self uploadAddressBook:jsonStr];
//
//}
////联系人数据转化为Json字符串
//-(NSString *)convertToJsonData:(NSDictionary *)dict
//
//{
//
//    NSError *error;
//
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
//
//    NSString *jsonString;
//
//    if (!jsonData) {
//
//        NSLog(@"%@",error);
//
//    }else{
//
//        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
//
//    }
//
//    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
//
//    NSRange range = {0,jsonString.length};
//
//    //去掉字符串中的空格
//
//    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
//
//    NSRange range2 = {0,mutStr.length};
//
//    //去掉字符串中的换行符
//
//    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
//
//    return mutStr;
//
//}
//
////把通讯录传给后台
//- (void)uploadAddressBook:(NSString *)jsonStr{
//
//    [ContactRequestLogic uploadAddressBookWith:jsonStr Success:^(NSDictionary * _Nonnull Dict) {
//        NSLog(@"上传结果 ：%@",Dict);
//        if (Dict[@"data"]) {
//            [self.addressBookFriendAry addObjectsFromArray:Dict[@"data"]];
//        }
//        NSLog(@"%@",Dict[@"message"]);
//    } failure:^(NSString * _Nonnull errMsg) {
//        NSLog(@"获取失败：%@",errMsg);
//    }];
//}

-(UIView*)tableHeaderView
{
    UIView * backView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    
    PublicButton * searchbtn =[[PublicButton  alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50) withButtonType:@"ContactorsVCButton"];
    searchbtn.tag=10086;
    [self setNewFriendNum:searchbtn];
    [searchbtn addTarget:self action:@selector(clickNewFriendsAction) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:searchbtn];
    PublicButton * publicBtn =[[PublicButton  alloc]initWithFrame:CGRectMake(0, searchbtn.bottom, SCREEN_WIDTH, 50) withButtonType:@"ContactorsPublicButton"];
       publicBtn.tag=10087;
       [publicBtn addTarget:self action:@selector(clickPublicAction) forControlEvents:UIControlEventTouchUpInside];
       [backView addSubview:publicBtn];
    return backView;
}
#pragma mark - ButtonEvent
-(void)clickNewFriendsAction
{

    NewFroendsViewController * vc =[[NewFroendsViewController alloc]init];
    vc.friendVCBlock = ^(NSString * _Nonnull eventType) {
        if ([eventType isEqualToString:@"refreshRedDot"]) {
            [self refreshNewFriendNum];
        }else if ([eventType isEqualToString:@"refreshFriendList"])
        {
            [self dealWithContactData];
        }
    };
      vc.hidesBottomBarWhenPushed = YES;
//    vc.addressBookFriends = (NSArray *)_addressBookFriendAry;
    [self.navigationController pushViewController:vc animated:YES];
      
}

- (void)clickPublicAction{
    PublicViewController * publicVC = [[PublicViewController alloc]init];
    publicVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:publicVC animated:YES];
}

- (void)sortAllContacts:(NSArray *)aContactList
{
    [self.dataSources removeAllObjects];
    [self.sectionTitles removeAllObjects];
    
    NSMutableArray *contactArray = [NSMutableArray arrayWithArray:aContactList];
    
    //建立索引的核心, 返回27，是a－z和＃
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];
    
    NSInteger highSection = [self.sectionTitles count];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i < highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }
    
    //按首字母分组
    for (ContactModel *contact in contactArray) {
        NSString *firstLetter = [EMChineseToPinyin pinyinFromChineseString:contact.nickname];
        NSInteger section;
        if (firstLetter.length > 0) {
            section = [indexCollation sectionForObject:[firstLetter substringToIndex:1] collationStringSelector:@selector(uppercaseString)];
        } else {
            section = [sortedArray count] - 1;
        }
        
        NSMutableArray *array = [sortedArray objectAtIndex:section];
        [array addObject:contact];
    }
    
    //每个section内的数组排序
    for (int i = 0; i < [sortedArray count]; i++) {
        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(ContactModel *contact1, ContactModel *contact2) {
            NSString *firstLetter1 = [EMChineseToPinyin pinyinFromChineseString:contact1.name];
            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
            
            NSString *firstLetter2 = [EMChineseToPinyin pinyinFromChineseString:contact2.name];
            firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
            
            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
        }];
        
        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
    }
    
    //去掉空的section
    for (NSInteger i = [sortedArray count] - 1; i >= 0; i--) {
        NSArray *array = [sortedArray objectAtIndex:i];
        if ([array count] == 0) {
            [sortedArray removeObjectAtIndex:i];
            [self.sectionTitles removeObjectAtIndex:i];
        }
    }
    
    [self.dataSources addObjectsFromArray:sortedArray];
}
#pragma mark -tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_contactsTable]) {
        return self.dataSources.count;
    }else
    {
        return self.groupDataSources.count;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([tableView isEqual:_contactsTable ]) {
        markIndx = 100;
        ContactModel * model =self.dataSources[indexPath.section][indexPath.row];
        FriendsInfoViewController* vc =[[FriendsInfoViewController alloc]init];
        vc.Fuuid = model.fuuid;
        vc.isFriend = 1;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else
    {
        markIndx = 101;
        ContactModel * model =self.groupDataSources[indexPath.section][indexPath.row];
        ChatViewController * ChatVC=[[ChatViewController alloc]init];
        ChatVC.chatType=ChatTypeGroup;
        ChatVC.receiverId=model.user_id;
        ChatVC.gk_navTitle=model.groupName;
        ChatVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:ChatVC animated:YES];
          
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_contactsTable]) {
        return [self.dataSources[section] count];
    }else
    {
        return [self.groupDataSources[section]count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_contactsTable]) {
        ContactsCell *cell = [ tableView dequeueReusableCellWithIdentifier:[ContactsCell cellIdentifier] forIndexPath:indexPath];
        if (!cell) {
            cell = [[ContactsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[ContactsCell cellIdentifier]];
        }
        cell.cellType=@"friend";
        cell.contactor = self.dataSources[indexPath.section][indexPath.row];
        return cell;
        
    }else
    {
        ContactsCell *cell = [ tableView dequeueReusableCellWithIdentifier:[ContactsCell cellIdentifier] forIndexPath:indexPath];
        if (!cell) {
            cell = [[ContactsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[ContactsCell cellIdentifier]];
        }
        cell.cellType=@"group";
        cell.contactor= self.groupDataSources[indexPath.section][indexPath.row];
        return cell;
    }
    
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if ([tableView isEqual:_contactsTable]) {
        return self.sectionTitles;
    }else
    {
        return [NSArray array];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 32;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = KHEXCOLOR(@"#F5F5F5")    ;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, tableView.frame.size.width - 20, 32)];
    label.backgroundColor = KHEXCOLOR(@"#F5F5F5");
    label.font = [UIFont systemFontOfSize:12];
    label.textColor=KHEXCOLOR(@"#999999");
    if ([tableView isEqual:_contactsTable]) {
        NSString *title = self.sectionTitles[section];
        label.text = [NSString stringWithFormat:@"  %@", title];
    }else
    {
        NSInteger num = [self.groupDataSources[section]count];
        if ([self.sectionType isEqualToString:@"0"]&&self.groupDataSources.count == 1) {
          label.text=[NSString stringWithFormat:@"我创建的群组(%ld)",num];
        }else if ([self.sectionType isEqualToString:@"1"]&&self.groupDataSources.count == 1){
           label.text=[NSString stringWithFormat:@"我加入的群组(%ld)",num];
        }else{
            if (section==0) {
                       label.text=[NSString stringWithFormat:@"我创建的群组(%ld)",num];;
                   }else
                   {
                       label.text=[NSString stringWithFormat:@"我加入的群组(%ld)",num];
                   }
        }
       
    }
    [view addSubview:label];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(void)setNewFriendNum:(PublicButton*)markBtn
{
    NSString * currentNum = [CacheTool readUserDefaults:[NSString stringWithFormat:@"system_tabbarNum_%@",[LoginManager shareLoginManager].userModel.fuuid]];
    if (![NSObject ldy_isEmpty:currentNum]) {
        if ([currentNum integerValue]>0) {
            markBtn.remarkLbl.hidden=NO;
            markBtn.remarkLbl.text=[NSString stringWithFormat:@"%@",currentNum];
        }
    }else
    {
        markBtn.remarkLbl.text=@"0";
        markBtn.remarkLbl.hidden=YES;
        [[LoginManager shareLoginManager].mainTabBar setRedDotWithIndex:1 ValueInteger:0 isShow:NO];
    }
}
#pragma mark - getter
- (UITableView *)contactsTable {
    if (!_contactsTable) {
        _contactsTable = [[UITableView alloc] init];
        _contactsTable.delegate = self;
        _contactsTable.dataSource = self;
        _contactsTable.tableFooterView = [UIView new];
        _contactsTable.rowHeight = 60.0f;
        [_contactsTable registerNib:[ContactsCell registerNib] forCellReuseIdentifier:[ContactsCell cellIdentifier]];
        _contactsTable.tableHeaderView=[self tableHeaderView];
    }
    return _contactsTable;
}

- (UIView *)navView {
    if (!_navView) {
        _navView = [[UIView alloc] init];
        _navView.frame = CGRectMake(0,0,90, 35);
        _navView.backgroundColor = [UIColor clearColor];
        [_navView configLayerWithBorderWidth:0 andWithCornerRadius:5 andWithBorderColor:[UIColor whiteColor]];
        for (int i=0; i<2; i++) {
            UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
            button.frame=CGRectMake(0+(40+10)*i, 0, 40, 35);
//            button.backgroundColor=[UIColor redColor];
            button.tag=i+100;
            if (i==0) {
                [button setTitle:@"好友" forState:UIControlStateNormal];
                button.titleLabel.font=kMainFont(15);
            }else
            {
                [button setTitle:@"群组" forState:UIControlStateNormal];
                button.titleLabel.font=kMainFont(15);
            }
            [button setTitleColor:KHEXCOLOR(@"#AFAFAF") forState:UIControlStateNormal];
            [button setTitleColor:KHEXCOLOR(@"#262B2F") forState:UIControlStateSelected];

            if (i==0) {
                button.selected=YES;
                button.titleLabel.font = kFont(18);
                markBtn=button;
            }
            [button addTarget:self action:@selector(ClickNavButton:) forControlEvents:UIControlEventTouchUpInside];
            [_navView addSubview:button];
        }

    }
    return _navView;
}
-(void)ClickNavButton:(UIButton*)sender
{
    
    sender.selected = !sender.selected;
    sender.titleLabel.font = sender.selected==NO?kMainFont(15):kFont(18);
    markBtn.titleLabel.font = kMainFont(15);    
    [self setAnimtiomL:sender.tag];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if([scrollView isKindOfClass:[UITableView class]])
    {
        //如果是tableview滑动
    }
    else
    {
        if ( scrollView.contentOffset.x ==0) {
            [self setAnimtiomL:100];
        }else if(scrollView.contentOffset.x==SCREEN_WIDTH)
        {
            [self setAnimtiomL:101];
        }
    }
}
-(void)setAnimtiomL:(NSInteger)num
{
    UIButton * btn = [self.navView viewWithTag:num];
    if (btn!=markBtn) {
        markBtn.selected=NO;
        btn.selected=YES;
        btn.titleLabel.font = kMainFont(18);
        markBtn.titleLabel.font = kMainFont(15);
        markBtn=btn;
    }else
    {
        markBtn.selected=YES;
    }
    [self.bgScrollView setContentOffset:CGPointMake(SCREEN_WIDTH*(num-100),0) animated:YES];
}
-(UIScrollView*)bgScrollView
{
    if (!_bgScrollView) {
        _bgScrollView=[[UIScrollView alloc]init];
//    WithFrame:CGRectMake(0,NavigationBarHeight, SCREEN_WIDTH,SCREEN_HEIGHT-NavigationBarHeight-EMVIEWBOTTOMMARGIN)];
        _bgScrollView.showsVerticalScrollIndicator=NO;
        _bgScrollView.showsHorizontalScrollIndicator=NO;
        _bgScrollView.backgroundColor=KHEXCOLOR(@"#F4F4F4");
        _bgScrollView.pagingEnabled=YES;
        _bgScrollView.delegate=self;
        [_bgScrollView setContentSize:CGSizeMake(kScreenWidth*2, 0)];
    }
    return _bgScrollView;
}
- (UITableView *)groupsTable {
    if (!_groupsTable) {
        _groupsTable = [[UITableView alloc] init];
        _groupsTable.delegate = self;
        _groupsTable.dataSource = self;
//        UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
//        headView.backgroundColor= KHEXCOLOR(@"#F4F4F4");
        _groupsTable.tableFooterView = [UIView new];
        _groupsTable.rowHeight = 60.0f;
        _groupsTable.backgroundColor = KHEXCOLOR(@"#F4F4F4");
        [_groupsTable registerNib:[ContactsCell registerNib] forCellReuseIdentifier:[ContactsCell cellIdentifier]];
                _contactsTable.tableHeaderView=[self tableHeaderView];
    }
    return _groupsTable;
}
- (NSMutableArray *)dataSources {
    if (!_dataSources) {
        _dataSources = [NSMutableArray new];
    }
    return _dataSources;
}
- (NSMutableArray *)groupDataSources {
    if (!_groupDataSources) {
        _groupDataSources = [NSMutableArray new];
    }
    return _groupDataSources;
}

- (NSMutableArray<NSString *> *)sectionTitles{
    if (!_sectionTitles) {
        _sectionTitles = [NSMutableArray array];
    }
    return _sectionTitles;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(MJTableViewNullDataView*)nullDataView {
    if (!_nullDataView) {
        _nullDataView=[[MJTableViewNullDataView alloc]initWithFrame:CGRectMake(0,120, SCREEN_WIDTH, self.groupsTable.frame.size.height-60)];
        _nullDataView.hidden=YES;
        _nullDataView.backgroundColor=KHEXCOLOR(@"#F4F4F4");
    }
    [_nullDataView setCustomViewFrame:@"空状态" message:@"暂时没有群组"];
    return _nullDataView;
}

//-(NSMutableArray *)addressBookFriendAry{
//    if (!_addressBookFriendAry) {
//        _addressBookFriendAry = [NSMutableArray array];
//    }
//    return _addressBookFriendAry;
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
